package org.gim.controller.user;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.gim.common.CommonResult;
import org.gim.entity.dto.user.UserInfo;
import org.gim.entity.req.user.UserLoginReq;
import org.gim.service.user.IUserInfoService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static org.gim.common.enums.CommonEnum.USER_INFO_OFFLINE_STATUS;
import static org.gim.common.enums.CommonEnum.USER_INFO_ONLINE_STATUS;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserInfoController {


    @Resource
    private IUserInfoService userInfoService;

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/doLogin")
    public CommonResult doLogin(@RequestBody @Validated UserLoginReq userLoginReq) {


        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",userLoginReq.getPhone());

        UserInfo userInfo = userInfoService.getOne(queryWrapper);

        if(ObjectUtil.isNull(userInfo)){
            return CommonResult.errorResponse("用户不存在");
        }

        if(!userInfo.getPassWord().equals(userLoginReq.getPassWord())){
            return CommonResult.errorResponse("密码错误");
        }

        StpUtil.login(userInfo.getUserId());

        userInfo.setStatus(USER_INFO_ONLINE_STATUS.getValue());

        userInfoService.updateById(userInfo);

        String token = StpUtil.getTokenValue();

        Map map = new HashMap();
        map.put("token",token);
        map.put("userInfo",userInfo);

        return CommonResult.successResponse(map,"登录成功");

    }

    @GetMapping("/isLogin")
    public String isLogin() {
        String userId = String.valueOf(StpUtil.getLoginIdAsLong());
        log.info("当前登录用户：{}", userId);
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    @GetMapping("/logout")
    public CommonResult<String> logout(@RequestParam("userId") String userId) {
        StpUtil.logout(userId);

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);

        UserInfo userInfo = userInfoService.getOne(queryWrapper);

        userInfo.setStatus(USER_INFO_OFFLINE_STATUS.getValue());

        userInfoService.updateById(userInfo);

        log.info("当前登录用户:{}，退出登录成功！",userId);
        return CommonResult.successResponse("注销成功");
    }

}
